/**
 * 车辆本地存储管理工具函数
 * 提供车辆数据的增删改查操作
 */

// 存储键名常量
const STORAGE_KEYS = {
  VEHICLES: 'user_vehicles',
  DEFAULT_VEHICLE_ID: 'default_vehicle_id'
}

/**
 * 生成唯一ID
 * @returns {string} UUID字符串
 */
function generateVehicleId() {
  return 'vehicle_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11)
}

/**
 * 获取所有车辆
 * @returns {Array} 车辆列表
 */
function getAllVehicles() {
  try {
    const vehicles = uni.getStorageSync(STORAGE_KEYS.VEHICLES)
    return Array.isArray(vehicles) ? vehicles : []
  } catch (error) {
    console.error('获取车辆列表失败:', error)
    return []
  }
}

/**
 * 根据ID获取车辆
 * @param {string} id 车辆ID
 * @returns {Object|null} 车辆信息
 */
function getVehicleById(id) {
  try {
    const vehicles = getAllVehicles()
    return vehicles.find(vehicle => vehicle.id === id) || null
  } catch (error) {
    console.error('获取车辆信息失败:', error)
    return null
  }
}

/**
 * 添加车辆
 * @param {Object} vehicleData 车辆数据
 * @returns {Object} 操作结果
 */
function addVehicle(vehicleData) {
  try {
    const vehicles = getAllVehicles()
    
    // 检查车牌号是否重复
    if (isPlateNumberExists(vehicleData.plate_number)) {
      return {
        success: false,
        message: '该车牌号已存在'
      }
    }
    
    // 创建新车辆对象
    const newVehicle = {
      id: generateVehicleId(),
      plate_number: vehicleData.plate_number.toUpperCase(),
      vehicle_type: vehicleData.vehicle_type || 'small',
      brand: vehicleData.brand || '',
      model: vehicleData.model || '',
      color: vehicleData.color || '',
      is_default: vehicles.length === 0, // 第一辆车自动设为默认
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }
    
    vehicles.push(newVehicle)
    uni.setStorageSync(STORAGE_KEYS.VEHICLES, vehicles)
    
    // 如果是第一辆车，设为默认车辆
    if (newVehicle.is_default) {
      uni.setStorageSync(STORAGE_KEYS.DEFAULT_VEHICLE_ID, newVehicle.id)
    }
    
    return {
      success: true,
      message: '车辆添加成功',
      data: newVehicle
    }
  } catch (error) {
    console.error('添加车辆失败:', error)
    return {
      success: false,
      message: '添加车辆失败，请重试'
    }
  }
}

/**
 * 更新车辆信息
 * @param {string} id 车辆ID
 * @param {Object} vehicleData 更新的车辆数据
 * @returns {Object} 操作结果
 */
function updateVehicle(id, vehicleData) {
  try {
    const vehicles = getAllVehicles()
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === id)
    
    if (vehicleIndex === -1) {
      return {
        success: false,
        message: '车辆不存在'
      }
    }
    
    // 如果修改了车牌号，检查是否重复
    if (vehicleData.plate_number && 
        vehicleData.plate_number !== vehicles[vehicleIndex].plate_number &&
        isPlateNumberExists(vehicleData.plate_number, id)) {
      return {
        success: false,
        message: '该车牌号已存在'
      }
    }
    
    // 更新车辆信息
    const updatedVehicle = {
      ...vehicles[vehicleIndex],
      ...vehicleData,
      plate_number: vehicleData.plate_number ? vehicleData.plate_number.toUpperCase() : vehicles[vehicleIndex].plate_number,
      updated_at: new Date().toISOString()
    }
    
    vehicles[vehicleIndex] = updatedVehicle
    uni.setStorageSync(STORAGE_KEYS.VEHICLES, vehicles)
    
    return {
      success: true,
      message: '车辆信息更新成功',
      data: updatedVehicle
    }
  } catch (error) {
    console.error('更新车辆失败:', error)
    return {
      success: false,
      message: '更新车辆失败，请重试'
    }
  }
}

/**
 * 删除车辆
 * @param {string} id 车辆ID
 * @returns {Object} 操作结果
 */
function deleteVehicle(id) {
  try {
    const vehicles = getAllVehicles()
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === id)
    
    if (vehicleIndex === -1) {
      return {
        success: false,
        message: '车辆不存在'
      }
    }
    
    const deletedVehicle = vehicles[vehicleIndex]
    vehicles.splice(vehicleIndex, 1)
    uni.setStorageSync(STORAGE_KEYS.VEHICLES, vehicles)
    
    // 如果删除的是默认车辆，重新设置默认车辆
    if (deletedVehicle.is_default && vehicles.length > 0) {
      setDefaultVehicle(vehicles[0].id)
    } else if (vehicles.length === 0) {
      // 如果没有车辆了，清除默认车辆ID
      uni.removeStorageSync(STORAGE_KEYS.DEFAULT_VEHICLE_ID)
    }
    
    return {
      success: true,
      message: '车辆删除成功'
    }
  } catch (error) {
    console.error('删除车辆失败:', error)
    return {
      success: false,
      message: '删除车辆失败，请重试'
    }
  }
}

/**
 * 设置默认车辆
 * @param {string} id 车辆ID
 * @returns {Object} 操作结果
 */
function setDefaultVehicle(id) {
  try {
    const vehicles = getAllVehicles()
    const vehicleIndex = vehicles.findIndex(vehicle => vehicle.id === id)
    
    if (vehicleIndex === -1) {
      return {
        success: false,
        message: '车辆不存在'
      }
    }
    
    // 清除所有车辆的默认状态
    vehicles.forEach(vehicle => {
      vehicle.is_default = false
    })
    
    // 设置新的默认车辆
    vehicles[vehicleIndex].is_default = true
    vehicles[vehicleIndex].updated_at = new Date().toISOString()
    
    uni.setStorageSync(STORAGE_KEYS.VEHICLES, vehicles)
    uni.setStorageSync(STORAGE_KEYS.DEFAULT_VEHICLE_ID, id)
    
    return {
      success: true,
      message: '默认车辆设置成功',
      data: vehicles[vehicleIndex]
    }
  } catch (error) {
    console.error('设置默认车辆失败:', error)
    return {
      success: false,
      message: '设置默认车辆失败，请重试'
    }
  }
}

/**
 * 获取默认车辆
 * @returns {Object|null} 默认车辆信息
 */
function getDefaultVehicle() {
  try {
    const defaultVehicleId = uni.getStorageSync(STORAGE_KEYS.DEFAULT_VEHICLE_ID)
    if (!defaultVehicleId) {
      return null
    }
    
    return getVehicleById(defaultVehicleId)
  } catch (error) {
    console.error('获取默认车辆失败:', error)
    return null
  }
}

/**
 * 检查车牌号是否重复
 * @param {string} plateNumber 车牌号
 * @param {string} excludeId 排除的车辆ID（用于编辑时排除自己）
 * @returns {boolean} 是否重复
 */
function isPlateNumberExists(plateNumber, excludeId = null) {
  try {
    const vehicles = getAllVehicles()
    return vehicles.some(vehicle => 
      vehicle.plate_number === plateNumber.toUpperCase() && 
      vehicle.id !== excludeId
    )
  } catch (error) {
    console.error('检查车牌号重复失败:', error)
    return false
  }
}

/**
 * 清空所有车辆数据
 * @returns {Object} 操作结果
 */
function clearAllVehicles() {
  try {
    uni.removeStorageSync(STORAGE_KEYS.VEHICLES)
    uni.removeStorageSync(STORAGE_KEYS.DEFAULT_VEHICLE_ID)
    
    return {
      success: true,
      message: '车辆数据清空成功'
    }
  } catch (error) {
    console.error('清空车辆数据失败:', error)
    return {
      success: false,
      message: '清空车辆数据失败，请重试'
    }
  }
}

/**
 * 获取车辆统计信息
 * @returns {Object} 统计信息
 */
function getVehicleStats() {
  try {
    const vehicles = getAllVehicles()
    const stats = {
      total: vehicles.length,
      hasDefault: vehicles.some(vehicle => vehicle.is_default),
      typeStats: {}
    }
    
    // 统计各类型车辆数量
    vehicles.forEach(vehicle => {
      const type = vehicle.vehicle_type || 'unknown'
      stats.typeStats[type] = (stats.typeStats[type] || 0) + 1
    })
    
    return stats
  } catch (error) {
    console.error('获取车辆统计失败:', error)
    return {
      total: 0,
      hasDefault: false,
      typeStats: {}
    }
  }
}

// 导出所有函数
export {
  generateVehicleId,
  getAllVehicles,
  getVehicleById,
  addVehicle,
  updateVehicle,
  deleteVehicle,
  setDefaultVehicle,
  getDefaultVehicle,
  isPlateNumberExists,
  clearAllVehicles,
  getVehicleStats,
  STORAGE_KEYS
}

// 默认导出
export default {
  generateVehicleId,
  getAllVehicles,
  getVehicleById,
  addVehicle,
  updateVehicle,
  deleteVehicle,
  setDefaultVehicle,
  getDefaultVehicle,
  isPlateNumberExists,
  clearAllVehicles,
  getVehicleStats,
  STORAGE_KEYS
}